package com.bezdelnick.forum.web.model;

import com.bezdelnick.forum.domain.ModelBean;
import com.bezdelnick.forum.domain.Subtype;
import com.bezdelnick.forum.domain.Type;
import com.bezdelnick.forum.service.ForumService;
import org.apache.wicket.model.IModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.spring.injection.annot.SpringComponentInjector;
import org.springframework.beans.factory.annotation.Autowired;

import javax.swing.event.TreeModelListener;
import javax.swing.tree.*;
import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: Bezdelnick
 * Date: 25.07.12
 * Time: 11:21
 * To change this template use File | Settings | File Templates.
 */
public class NavigationTreeModel extends DefaultTreeModel {

    @SpringBean
    @SuppressWarnings("unused")
    private ForumService forumService;

    public NavigationTreeModel(TreeNode root) {
        super(root);
        /* Add this instance to Spring context */
        SpringComponentInjector.get().inject(this);

        this.setRoot(root);

        Map<String, Object> map = new HashMap<String, Object>();
        List<Type> types = forumService.getTypeDao().loadTypes();

        for (Type type : types) {
            List<Subtype> subtypes = forumService.getSubtypeDao().loadSubtypesByTypeId(type.getId());
            map.put(type.getName(), subtypes);
        }

        addFolders((DefaultMutableTreeNode) this.root, map);
    }

    private void addFolders(DefaultMutableTreeNode parent, Map<String, Object> sub) {
        Set<String> keys = sub.keySet();

        for (String key : keys) {
            if (sub.get(key) instanceof Map) {
                DefaultMutableTreeNode child = new DefaultMutableTreeNode(new ModelBean(key));
                parent.add(child);
                addFolders(child, (Map<String, Object>) sub.get(key));
            }

            if (sub.get(key) instanceof List) {
                DefaultMutableTreeNode child = new DefaultMutableTreeNode(new ModelBean(key));
                parent.add(child);
                addDocuments(child, (List<Object>) sub.get(key));
            }
        }
    }

    private void addDocuments(DefaultMutableTreeNode parent, List<Object> sub) {
        for (Object obj : sub) {
            DefaultMutableTreeNode child = null;

            if (obj.getClass().equals(Subtype.class)) {
                child = new DefaultMutableTreeNode(new ModelBean(((Subtype) obj).getName()));
            } else {
                child = new DefaultMutableTreeNode(new ModelBean(obj.toString()));
            }

            parent.add(child);
        }
    }
}
